package com.imgo.max.fans.listener;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.imgo.max.artist.constant.FansMQTagConstant;
import com.imgo.max.artist.dto.CancelCollectHisDto;
import com.imgo.max.artist.dto.DevoteInfo;
import com.imgo.max.chatV3.service.ChatV3Service;
import com.imgo.max.common.dto.ResultDO;
import com.imgo.max.common.log.CustomLogger;
import com.imgo.max.common.log.CustomLoggerFactory;
import com.imgo.max.common.result.ModuleResultCode;
import com.imgo.max.common.util.LoggerUtils;
import com.imgo.max.common.util.ObjectUtil;
import com.imgo.max.core.tools.Collections3;
import com.imgo.max.experience.dto.UserExperienceDto;
import com.imgo.max.experience.service.GeneralExperienceService;
import com.imgo.max.fans.dao.CancelCollectHisDao;
import com.imgo.max.fans.dao.FansNumDao;
import com.imgo.max.fans.dao.FocusArtistDao;
import com.imgo.max.fans.mapping.CancelCollectHis;
import com.imgo.max.fans.mapping.FansNum;
import com.imgo.max.fans.mapping.FocusArtist;
import com.imgo.max.popularity.service.PopularityMessageService;
import com.imgo.max.user.dto.User;
import com.imgo.max.user.service.UserCacheService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

public class FansMsgListener implements MessageListener {

    private static final CustomLogger logger = CustomLoggerFactory.getLogger(FansMsgListener.class);

    @Resource
    private FocusArtistDao focusArtistDao;
    @Resource
    private CancelCollectHisDao cancelCollectHisDao;
    @Resource
    private FansNumDao fansNumDao;
    @Resource
    private PopularityMessageService popularityMessageService;
    @Autowired
    FansMsgHandler fansMsgHandler;
    @Resource
    private GeneralExperienceService generalExperienceService;
    @Resource
    UserCacheService userCacheService;
    @Resource
    ChatV3Service chatV3Service;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {

        byte[] body = message.getBody();
        String msgId = message.getMsgID();
        String tag = message.getTag();
        try {
            if (tag.equals(FansMQTagConstant.TAG_INSERT_CANCEL_COLLECT_HISTORY)) {
                CancelCollectHisDto cancelCollectHis = (CancelCollectHisDto) ObjectUtil.toObject(body);
                insertCancelCollectHis(cancelCollectHis);
            } else {
                String msg = new String(body);
                String uid = null;
                if (tag.equals(FansMQTagConstant.TAG_CANCEL_COLLECT_ALL_ARTISTS)) {
                    uid = msg;
                    cancelCollectArtists(uid);
                } else {
                    String[] msgArr = msg.split(":");
                    uid = msgArr[0];
                    String artistUid = "";
                    if (msgArr.length > 1) {
                        artistUid = msgArr[1];
                    }
                    if (tag.equals(FansMQTagConstant.TAG_CANCEL_COLLECT_ARTIST)) {
                        cancelCollectArtist(uid, artistUid);
                    } else if (tag.equals(FansMQTagConstant.TAG_COLLECT_ARTISTS)) {
                        collectArtist(uid, artistUid);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Action.ReconsumeLater;
        }
        return Action.CommitMessage;
    }

    /**
     * 添加关注接口：
     */
    @Transactional
    public void collectArtist(String uid, String artistId) {
        if (StringUtils.isBlank(uid) || StringUtils.isBlank(artistId)) {
            return;
        }
        try {
            fansMsgHandler.collectArtistRedisOperate(uid, artistId);

            String[] split = artistId.split(",");
            for (String artId : split) {
                FocusArtist ar = new FocusArtist();
                ar.setFocus_uid(uid);
                ar.setBefocus_uid(artId);
                List<FocusArtist> arl = focusArtistDao.selectIfCollect(ar);
                // 去除重复关注
                if (null != arl && arl.size() > 0) {
                    continue;
                }
                ar.setFocus_time(new Date());
                // TODO 建一个常量表示
                ar.setFocus_status(1);
                try {
                    Integer integer = focusArtistDao.addFans(ar);
                    if (0 == integer) {
                        return;
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    return;
                }

                List<FocusArtist> fansNumEntity = focusArtistDao.getFansNumEntity(artId);
                // 存在增加粉丝数
                // 不存在插入一条数据，粉丝数为1
                if (null == fansNumEntity || fansNumEntity.size() == 0) {
                    FansNum fn = new FansNum();
                    fn.setFansNum(1);
                    fn.setArtistUid(artId);
                    fansNumDao.insert(fn);
                } else {
                    fansNumDao.updatefanNum(artId);
                }

                // 关注人气值增加
                DevoteInfo devote = devoteInfoCreator(artId, uid, 10);
//				popularityMessageService.updatePopularity(devote);

                try {
                    // 发送关注消息
                    ResultDO<UserExperienceDto> userExperienceDtoResultDO = generalExperienceService.getUserExperience(uid);
                    ResultDO<User> userResultDO = userCacheService.queryUserByUid(uid);
                    if (ResultDO.isSuccess(userExperienceDtoResultDO) && ResultDO.isSuccess(userResultDO)) {
                        UserExperienceDto userExperienceDto = userExperienceDtoResultDO.getModule();
                        User user = userResultDO.getModule();
                        if (userExperienceDto != null && user != null) {
                            int role = userExperienceDto.getRole() != null ? Integer.parseInt(userExperienceDto.getRole()) : 0;
                            int level = userExperienceDto.getLevel() != null ? userExperienceDto.getLevel().intValue() : 1;
                            chatV3Service.fansNotice(artistId, uid, role, level, user.getNickName());
                        }
                    }
                } catch (Exception e) {
                    LoggerUtils.error(logger, e, ModuleResultCode.FANS, uid, artistId);
                }
            }
        } catch (Exception e) {
            LoggerUtils.error(logger, e, ModuleResultCode.FANS, uid, artistId);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    /**
     * 取消用户关注所有艺人
     *
     * @param uid
     * @return
     */
    @Transactional
    public void cancelCollectArtists(String uid) {
        if (StringUtils.isBlank(uid)) {
            return;
        }
        try {
            // 获得所有关注艺人的id
            List<FocusArtist> artistidlist = focusArtistDao.selectByUid(uid, null);
            if (Collections3.isNotEmpty(artistidlist)) {
                for (FocusArtist fouArtist : artistidlist) {
                    // 解除关注关系
                    cancelCollectArtist(uid, fouArtist.getBefocus_uid());
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Transactional
    private void cancelCollectArtist(String uid, String artistUid) {
        try {
            fansMsgHandler.cancelCollectArtistRedisOperate(uid, artistUid);
            // 删除 max_focus_artist 表中对应记录
            int i = focusArtistDao.deleteFans(uid, artistUid);
            if (i == 0) {
                // 没有对应记录被删除、原因逻辑是返回指定艺人的粉丝数量
                // int fansNum = focusArtistDao.getFansNum(artistUid);
            } else {
                // 添加一条删除历史记录到历史表
                this.insertCancelCollectHis(uid, artistUid, "", uid + "," + artistUid, "max_focus_artist");// 记录到历史表中

                try {
                    // 指定艺人粉丝数 -1
                    fansNumDao.updateByCancel(artistUid);
                    this.insertCancelCollectHis(uid, artistUid, "-1", artistUid + ",-1", "max_fans_num");// 记录到历史表中
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                // 取消关注人气值减少
                DevoteInfo devote = devoteInfoCreator(artistUid, uid, -10);

                if (devote != null) {
//					popularityMessageService.updatePopularity(devote);
                    this.insertCancelCollectHis(uid, artistUid, "-10", artistUid + "," + uid + "," + -10, "ranklist");// 记录到历史表中
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 取消关注记录到历史表中
     *
     * @param content
     * @param type
     * @return Integer
     */
    private Integer insertCancelCollectHis(String uid, String artistUid, String val, String content, String type) {
        CancelCollectHisDto cancelCollectHis = new CancelCollectHisDto();
        cancelCollectHis.setUid(uid);
        cancelCollectHis.setArtistUid(artistUid);
        cancelCollectHis.setVal(val);
        cancelCollectHis.setContent(content);
        cancelCollectHis.setType(type);
        cancelCollectHis.setCreateTime(new Date());
        return insertCancelCollectHis(cancelCollectHis);
    }

    private Integer insertCancelCollectHis(CancelCollectHisDto cancelCollectHis) {
        Integer conut = null;
        if (cancelCollectHis == null)
            return -1;
        CancelCollectHis his = new CancelCollectHis();
        his.setUid(cancelCollectHis.getUid());
        his.setArtistuid(cancelCollectHis.getArtistUid());
        his.setVal(cancelCollectHis.getVal());
        his.setContent(cancelCollectHis.getContent());
        his.setType(cancelCollectHis.getType());
        his.setCreatetime(cancelCollectHis.getCreateTime());
        try {
            conut = cancelCollectHisDao.insertCancelCollectHis(his);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return conut;
    }

    private DevoteInfo devoteInfoCreator(String artistUid, String uid, int devoteVal) {
        if (StringUtils.isBlank(artistUid) || StringUtils.isBlank(uid)) {
            return null;
        }
        // 取消关注人气值减少
        DevoteInfo devote = new DevoteInfo();
        devote.setArtistUid(artistUid);
        devote.setUid(uid);
        devote.setDevoteValue(devoteVal);
        // 0:加粉丝 1:礼物 2:守护
        devote.setType(0);
        devote.setTime(new Timestamp(System.currentTimeMillis()));
        return devote;
    }

}
